<template>
  <!--菜单
  <el-radio-group v-model="isCollapse" style="margin-bottom: 20px;">
    <el-radio-button :label="false">展开</el-radio-button>
    <el-radio-button :label="true">收起</el-radio-button>
  </el-radio-group>:collapse="isCollapse"-->
  <el-menu
    ref="domMenu"
    :default-active="index"
    class="el-menu-vertical-demo"
    @select="select"
    @open="handleOpen"
    @close="handleClose">
      <el-submenu
        v-for="item in menu.filter(a => a.parentId===0)"
        :key="'menu_' + item.id"
        :index="item.id"
      >
        <template #title>
          <i :class="item.icon"></i>
          <span>{{item.title}}</span>
        </template>
        <el-menu-item-group>
          <el-menu-item
            v-for="item2 in menu.filter(a => a.parentId===item.id)"
            :key="'submenu_' + item2.id"
            :index="item2.id"
          >{{item2.title}}</el-menu-item>
        </el-menu-item-group>
      </el-submenu>
  </el-menu>
</template>

<script>
// 模块菜单
import { onMounted, watch, ref } from 'vue'

// 状态
// eslint-disable-next-line import/no-absolute-path
import VueDS from '/nf-state'

</script>

<script setup>
// 菜单数据
// eslint-disable-next-line import/no-absolute-path
import { menu } from '/jsonPlat/menu.json'

// 是否折叠菜单
const isCollapse = ref(false)

// 访问状态
const { get } = VueDS.useStore()
// 注册 tab 的状态
const tabState = get.tabState()
tabState.menu = menu

const index = ref(100)
const domMenu = ref(null)
// 点击菜单触发的 hash 变化
let isMenuSetHash = true

onMounted(() => {
  domMenu.value.open('100')
  domMenu.value.open('101')
})

// 二级菜单被选中
const select = (index, indexPath) => {
  console.log('当前激活节点', index, indexPath)
  // 设置状态，交给 tab 组件处理，tab 会监听
  tabState.trigger = 'menu'
  tabState.activeModuleId = parseInt(index)
  location.hash = '#' + tabState.activeModuleId
  isMenuSetHash = true
}

const handleOpen = (key, keyPath) => {
  console.log(key, keyPath)
}

const handleClose = (key, keyPath) => {
  console.log(key, keyPath)
}

// 做个简单的路由
const location = window.location
const oldURL = location.href
const hash = location.hash
console.log('======== location', location)
console.log('======== hash', hash)

// 监听 hash 变化
window.onhashchange = (arg) => {
  console.log('======== onhashchange', arg)
  const hash = location.hash
  console.log('======== hash', hash)
  if (isMenuSetHash) {
    // 菜单触发
    console.log('======== 菜单触发', hash)
    isMenuSetHash = false
  } else {
    // url地址栏 触发
    console.log('======== url地址栏 触发', hash)
    tabState.trigger = 'url'
    tabState.activeModuleId = parseInt(hash.replace('#', ''))
  }
}

</script>

<style>
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
  }
</style>
